
<template>
	<view class="product-detail-container">
		<!-- 顶部导航栏 -->
		<u-navbar title="商品详情" :border-bottom="false" bg-color="#ffffff" title-color="#000000" :left-icon="'arrow-left'"
			@left-click="goBack" :fixed="true" :auto-back="true">
			<template #right>
				<view class="navbar-right">
					<u-icon name="star" size="20" color="#666" @click="toggleFavorite"></u-icon>
					<u-icon name="share" size="20" color="#666" @click="shareProduct"
						style="margin-left: 15px"></u-icon>
				</view>
			</template>
		</u-navbar>

		<!-- 商品图片轮播 -->
		<view class="product-images-section">
			<swiper class="product-swiper" :indicator-dots="true" indicator-color="rgba(255,255,255,0.5)"
				indicator-active-color="#1abc9c">
				<swiper-item v-for="(image, index) in (product.images || [])" :key="index">
					<image class="product-image" :src="image" mode="aspectFill"></image>
				</swiper-item>
			</swiper>
		</view>

		<!-- 限时抢购横幅 -->
		<view v-if="product.isFlashSale" class="flash-sale-banner">
			<view class="banner-content">
				<view class="banner-left">
					<text class="banner-title">限时购</text>
					<view class="banner-price">
						<text class="current-price-text">¥ {{ product.currentPrice }}</text>
						<text class="original-price-text">¥ {{ product.originalPrice }}</text>
					</view>
				</view>
				<view class="banner-right">
					<text class="countdown-label">距离结束</text>
					<view class="countdown-timer">
						<text class="countdown-item">{{ countdown.hours }}</text>
						<text class="countdown-separator">:</text>
						<text class="countdown-item">{{ countdown.minutes }}</text>
						<text class="countdown-separator">:</text>
						<text class="countdown-item">{{ countdown.seconds }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 商品基本信息 -->
		<view class="product-info-section">
			<view v-if="!product.isFlashSale" class="price-section">
				<text class="current-price">¥{{ product.currentPrice }}</text>
			</view>

			<text class="product-title">{{ product.title }}</text>
			<text class="product-subtitle">{{ product.subtitle }}</text>
		</view>

		<!-- 规格选择 + 评论 -->
		<view class="specification-section">
			<u-button @click="showSpecModal = true">选择规格</u-button>

			<view class="spec-item" @click="showSpecModal = true">
				<text class="spec-label">数量</text>
				<view class="spec-value">
					<text class="selected-quantity">{{ selectedQuantity }}件</text>
					<u-icon name="arrow-right" size="16" color="#999"></u-icon>
				</view>
			</view>

			<!-- 商品评论 -->
			<view class="comments-section" @click.stop="goToComments">
				<view class="comments-header">
					<text class="comments-title">商品评论</text>
					<view class="comments-info">
						<text class="comments-count">{{ commentTotal }}条评论</text>
						<u-icon name="arrow-right" size="16" color="#999"></u-icon>
					</view>
				</view>

				<view v-if="productComments.length > 0" class="comments-preview">
					<view v-for="(comment, index) in productComments.slice(0, 2)" :key="comment.id || index"
						class="comment-preview-item">
						<view class="comment-user">
							<image class="comment-avatar" :src="comment.avatar" mode="aspectFill"></image>
							<view class="comment-user-info">
								<text class="comment-username">{{ comment.username }}</text>
								<view class="comment-rating">
									<u-icon v-for="i in 5" :key="i" :name="i <= comment.rating ? 'star-fill' : 'star'"
										size="10" :color="i <= comment.rating ? '#ff6b35' : '#ddd'"></u-icon>
								</view>
							</view>
						</view>

						<text class="comment-content-text">{{ comment.content }}</text>

						<view v-if="comment.images && comment.images.length" class="comment-images">
							<image v-for="(img, idx) in comment.images.slice(0, 3)" :key="idx" class="comment-img"
								:src="img" mode="aspectFill" @click.stop="previewCommentImages(comment.images, idx)" />
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 商品详情 -->
		<view class="detail-section">
			<view class="section-title">商品详情</view>
			<view class="detail-content">
				<text class="detail-text">{{ product.description }}</text>
				<view class="detail-images">
					<image v-for="(image, index) in (product.detailImages || [])" :key="index" class="detail-image"
						:src="image" mode="widthFix"></image>
				</view>
			</view>
		</view>

		<!-- 底部购买栏 -->
		<view class="bottom-action-bar">
			<view class="action-left">
				<view class="action-item" @click="goToCustomerService">
					<u-icon name="/static/kefu.png" size="20" color="#666"></u-icon>
					<text class="action-text">客服</text>
				</view>
				<view class="action-item" @click="goToCart">
					<u-icon name="shopping-cart" size="20" color="#666"></u-icon>
					<text class="action-text">购物车</text>
				</view>
				<view class="action-item" @click="toggleFavorite">
					<u-icon :name="isFavorite ? 'star-fill' : 'star'" size="20"
						:color="isFavorite ? '#1abc9c' : '#666'"></u-icon>
					<text class="action-text">收藏</text>
				</view>
			</view>

			<view class="action-right">
				<!-- 	<u-button type="primary" size="large" class="add-cart-btn" @click="addToCart">
					加入购物车
				</u-button> -->
				<u-button type="primary" @click="addToCart">加入购物车</u-button>

				<u-button type="primary" size="large" class="buy-now-btn" @click="buyNow">
					立即购买
				</u-button>
			</view>
		</view>

		<specification-modal :visible="showSpecModal" :sku-list="skuList" @update:visible="showSpecModal = $event"
			@selectSku="onSkuSelected" @close="showSpecModal = false" />
	</view>
</template>

<script>
	import SpecificationModal from '@/components/specification-modal.vue'
	import {
		get,post
	} from '@/utils/request.js'


	export default {
		components: {
			SpecificationModal
		},
		data() {
			return {
				product: {
					id: '',
					title: '',
					subtitle: '',
					currentPrice: '',
					originalPrice: '',
					discount: '',
					salesCount: 0,
					description: '',
					images: [],
					detailImages: [],
					specifications: [],
					isFlashSale: false
				},
				skuList: [],
				selectedSpec: {},
				selectedQuantity: 1,
				selectedItems: [],
				showSpecModal: false,
				isFavorite: false,
				countdown: {
					hours: '02',
					minutes: '58',
					seconds: '28'
				},
				countdownTimer: null,
				productComments: [],
				commentPage: 1,
				commentPageSize: 10,
				commentTotal: 0,
				isLoadingComments: false,
				isLoadingPageData: false,
				skuId: 0,
			}
		},
		onLoad(options) {
			const productId = (options && options.id) || '133'
			this.commentPage = 1
			this.loadProductDetailAndComments(productId)
		},
		onUnload() {
			if (this.countdownTimer) {
				clearInterval(this.countdownTimer)
				this.countdownTimer = null
			}
		},
		onReachBottom() {
			if (this.product && this.product.id) {
				this.loadMoreComments(this.product.id)
			}
		},
		methods: {
			goBack() {
				uni.navigateBack({
					delta: 1
				})
			},
			goToCustomerService() {
				uni.navigateTo({
					url: '/pages/mySxz/onlineService/onlineService'
				})
			},
			goToCart() {
				uni.navigateTo({
					url: '/pages/cart/noTabBarCart'
				})
			},
			async toggleFavorite() {
			    const userId = uni.getStorageSync('userId');
			    // 先切换状态
			    this.isFavorite = !this.isFavorite;
			
			    try {
			        const res = await post('/core/favorites', { 
			            membersId: userId,
			            productId: this.product.id  // 注意是id小写还是Id
			        });
			
			        uni.showToast({
			            title: this.isFavorite ? '已收藏' : '已取消收藏',
			            icon: 'success'
			        });
			    } catch (error) {
			        // 如果请求失败，状态回滚
			        this.isFavorite = !this.isFavorite;
			        uni.showToast({
			            title: '操作失败',
			            icon: 'none'
			        });
			    }
			},

			shareProduct() {
				uni.showToast({
					title: '分享功能开发中',
					icon: 'none'
				})
			},
			async addToCart() {
				if (!this.skuId || this.skuId === 0) {
					this.showSpecModal = true;
				} else {
					const userId = uni.getStorageSync('userId');
					const res = await post('/transaction/item', {
						membersId: userId,
						skuId: this.skuId,
						quantity: this.selectedQuantity,
					});
					// 这里可以根据 res 做后续处理
					//console.log("添加购物车表中数据：", res);
				}
			},


			buyNow() {
				if (!this.skuId || this.skuId === 0) {
					this.showSpecModal = true;
					return;
				}


				const userId = uni.getStorageSync('userId');

				// 没有登录信息，跳转到登录页
				if (!userId) {
					uni.navigateTo({
						url: '/pages/Login/Login'
					});
					return;
				}

				//深拷贝，传递独立对象
				const selectedItem = JSON.parse(JSON.stringify(this.selectedItems))

				uni.navigateTo({
					url: `/pages/FillOrderDetail/FillOrderDetail?userId=${userId}`,
					success: () => {
						getApp().globalData = getApp().globalData || {};
						getApp().globalData.selectedItems = selectedItem;
					}
				});
			},

			goToComments() {
				uni.navigateTo({
					url: '/pages/product-detail/comments?id=' + this.product.id
				})
			},
			parseSpecSafe(spec) {
				if (!spec) return {}
				if (typeof spec === 'object') return spec
				try {
					return JSON.parse(spec)
				} catch (e) {
					console.warn('规格 JSON 解析失败', e)
					return {}
				}
			},
			mapApiItemToProduct(apiResponse = {}) {
				const item = (apiResponse && apiResponse.data !== undefined) ?
					apiResponse.data : (apiResponse || {})
				let skuList = Array.isArray(item.skuList) ? item.skuList :
					Array.isArray(item.skus) ? item.skus :
					(item.spu && Array.isArray(item.spu.skuList) ? item.spu.skuList : [])
				const parseSpecSafe = (specStr) => {
					try {
						return typeof specStr === 'string' ? JSON.parse(specStr) : (specStr || {})
					} catch (e) {
						console.warn('规格解析失败:', specStr, e)
						return {}
					}
				}
				skuList = skuList.map(sku => ({
					...sku,
					specObj: parseSpecSafe(sku.spec)
				}))
				const firstSku = skuList.length > 0 ? skuList[0] : {}
				const coalesce = (...values) => values.find(v => v !== undefined && v !== null && v !== '')
				const safeNormalizeImages = (imgs) => {
					if (!imgs) return []
					if (Array.isArray(imgs)) return imgs
					if (typeof imgs === 'string') return imgs.split(',').map(s => s.trim())
					return []
				}
				return {
					id: coalesce(item.id, item.spu?.id, ''),
					title: coalesce(item.spu?.name, item.name, firstSku.name, ''),
					subtitle: coalesce(item.brandName, item.subtitle, ''),
					currentPrice: coalesce(firstSku.price, item.price, 0),
					originalPrice: coalesce(firstSku.originalPrice, item.originalPrice, 0),
					salesCount: coalesce(item.salesCount, 0),
					stock: coalesce(item.stock, item.stockQuantity, 0),
					description: coalesce(item.description, item.detail, ''),
					images: safeNormalizeImages(item.imageUrls || item.imageUrl || item.images || firstSku.imageUrl),
					skuList,
					detailImages: safeNormalizeImages(item.detailImageUrls || item.detailImages),
					specifications: item.specifications || [],
					isFlashSale: !!(item.isFlashSale || item.skuIsFlashSale || false)
				}
			},
			async loadProductDetail(productId) {
				var id = productId || (this.product && this.product.id)
				try {
					const res = await get('/transaction/spu/withSku/' + id)
					const mapped = this.mapApiItemToProduct(res)
					this.product = mapped
					this.skuList = mapped.skuList || []
					var firstAvailable = (this.skuList || []).find((s) => s && s.stock > 0)
					if (firstAvailable) {
						this.selectedSku = firstAvailable
						var parts = []
						var specObj = firstAvailable.specObj || {}
						for (var k in specObj) {
							if (Object.prototype.hasOwnProperty.call(specObj, k)) {
								parts.push(k + ':' + specObj[k])
							}
						}
						this.selectedSpec = parts.join(' ')
					}
					this.startCountdown()
				} catch (err) {
					console.error('获取商品详情失败:', err)
				}
			},
			onSkuSelected({
				skuId,
				quantity,
				specs
			}) {
				this.skuId = skuId
				this.selectedQuantity = quantity

				// 关键：重新赋值一个全新的对象，断开与旧空对象的引用
				this.selectedSpec = {
					...specs
				}

				this.selectedItems = [{
					skuId: this.skuId,
					selectedQuantity: this.selectedQuantity || 1,
					selectedSpec: {
						...this.selectedSpec
					} // 再拷贝一份，避免后续修改影响
				}]
				
			},
			async loadOnlyComments(productId, isLoadMore) {
				var id = productId || (this.product && this.product.id)
				if (this.isLoadingComments) return
				this.isLoadingComments = true
				try {
					const res = await get('/transaction/YZMcomments/list', {
						spuId: id,
						pageNum: this.commentPage,
						pageSize: this.commentPageSize
					})
					var payload = (res && res.data && typeof res.data === 'object') ? res.data :
						(res && res.rows ? res : {})
					var rows = Array.isArray(payload.rows) ? payload.rows : []
					var total = Number(payload.total || rows.length) || 0
					var mapped = rows.map((item) => {
						var images = typeof item.images === 'string' ?
							item.images.split(',').map((s) => s.trim()).filter(Boolean) :
							(Array.isArray(item.images) ? item.images : [])
						return {
							id: item.id,
							username: (item.members && item.members.nickname) || item.username || '匿名用户',
							avatar: (item.members && item.members.avatar) ||
								'https://dummyimage.com/60x60/eee/999.png&text=U',
							rating: Number(item.rating) || 0,
							content: item.content || '',
							images: images
						}
					})
					if (isLoadMore) {
						this.productComments = this.productComments.concat(mapped)
					} else {
						this.productComments = mapped
					}
					this.commentTotal = total
				} catch (err) {
					console.error('获取商品评论失败:', err)
				} finally {
					this.isLoadingComments = false
				}
			},
			async loadProductDetailAndComments(productId) {
				var id = productId || (this.product && this.product.id)
				if (!id) return
				this.isLoadingPageData = true
				this.commentPage = 1
				try {
					await Promise.all([
						this.loadProductDetail(id),
						this.loadOnlyComments(id, false)
					])
				} catch (err) {
					console.error('加载商品或评论失败', err)
				} finally {
					this.isLoadingPageData = false
				}
			},
			loadMoreComments(productId) {
				if (this.productComments.length >= this.commentTotal) {
					uni.showToast({
						title: '没有更多评论了',
						icon: 'none'
					})
					return
				}
				this.commentPage++
				this.loadOnlyComments(productId, true)
			},
			previewCommentImages(urls, currentIndex) {
				if (!urls || !urls.length) return
				uni.previewImage({
					current: currentIndex || 0,
					urls: urls
				})
			},
			startCountdown() {
				if (!this.product.isFlashSale) return
				if (this.countdownTimer) {
					clearInterval(this.countdownTimer)
					this.countdownTimer = null
				}
				this.countdownTimer = setInterval(() => {
					var hours = parseInt(this.countdown.hours, 10)
					var minutes = parseInt(this.countdown.minutes, 10)
					var seconds = parseInt(this.countdown.seconds, 10)
					if (Number.isNaN(hours)) hours = 0
					if (Number.isNaN(minutes)) minutes = 0
					if (Number.isNaN(seconds)) seconds = 0
					seconds--
					if (seconds < 0) {
						seconds = 59;
						minutes--
					}
					if (minutes < 0) {
						minutes = 59;
						hours--
					}
					if (hours < 0) {
						clearInterval(this.countdownTimer)
						this.countdownTimer = null
						return
					}
					this.countdown = {
						hours: String(hours).padStart(2, '0'),
						minutes: String(minutes).padStart(2, '0'),
						seconds: String(seconds).padStart(2, '0')
					}
				}, 1000)
			}
		}
	}
</script>



<style lang="scss" scoped>
	.product-detail-container {
		background-color: #f8f8f8;
		min-height: 100vh;
		padding-bottom: 100px;
	}

	.navbar-right {
		display: flex;
		align-items: center;
		padding-right: 15px;
	}

	/* 限时抢购横幅样式 */
	.flash-sale-banner {
		background: linear-gradient(135deg, #e74c3c, #c0392b);
		padding: 15px;
		color: #ffffff;
	}

	.banner-content {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.banner-left {
		display: flex;
		flex-direction: column;
	}

	.banner-title {
		font-size: 16px;
		font-weight: bold;
		margin-bottom: 5px;
	}

	.banner-price {
		display: flex;
		align-items: center;
		gap: 8px;
	}

	.current-price-text {
		font-size: 18px;
		font-weight: bold;
	}

	.original-price-text {
		font-size: 14px;
		text-decoration: line-through;
		opacity: 0.8;
	}

	.banner-right {
		display: flex;
		flex-direction: column;
		align-items: flex-end;
	}

	.countdown-label {
		font-size: 12px;
		margin-bottom: 5px;
		opacity: 0.9;
	}

	.countdown-timer {
		display: flex;
		align-items: center;
		gap: 2px;
	}

	.countdown-item {
		background-color: rgba(255, 255, 255, 0.2);
		padding: 4px 6px;
		border-radius: 4px;
		font-size: 14px;
		font-weight: bold;
		min-width: 20px;
		text-align: center;
	}

	.countdown-separator {
		font-size: 14px;
		font-weight: bold;
		margin: 0 2px;
	}

	.product-images-section {
		width: 100%;
		height: 400px;
		background-color: #ffffff;
	}

	.product-swiper {
		width: 100%;
		height: 100%;
	}

	.product-image {
		width: 100%;
		height: 100%;
	}

	.product-info-section {
		background-color: #ffffff;
		padding: 20px 15px;
		margin-bottom: 10px;
	}

	.price-section {
		display: flex;
		align-items: center;
		margin-bottom: 15px;
	}

	.current-price {
		font-size: 24px;
		font-weight: bold;
		color: #1abc9c;
		margin-right: 10px;
	}

	.original-price {
		font-size: 16px;
		color: #999999;
		text-decoration: line-through;
		margin-right: 10px;
	}

	.discount-tag {
		background: linear-gradient(135deg, #1abc9c, #16a085);
		color: #ffffff;
		font-size: 12px;
		padding: 4px 8px;
		border-radius: 12px;
	}

	.product-title {
		font-size: 18px;
		font-weight: bold;
		color: #333333;
		line-height: 1.4;
		margin-bottom: 8px;
		display: block;
	}

	.product-subtitle {
		font-size: 14px;
		color: #666666;
		margin-bottom: 15px;
		display: block;
	}

	.sales-info {
		display: flex;
		justify-content: space-between;
	}

	.sales-text,
	.stock-text {
		font-size: 12px;
		color: #999999;
	}

	.specification-section {
		background-color: #ffffff;
		padding: 15px;
		margin-bottom: 10px;
	}

	.spec-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 12px 0;
		border-bottom: 1px solid #f0f0f0;

		&:last-child {
			border-bottom: none;
		}
	}

	.spec-label {
		font-size: 14px;
		color: #333333;
	}

	.spec-value {
		display: flex;
		align-items: center;
	}

	.selected-spec,
	.selected-quantity {
		font-size: 14px;
		color: #666666;
		margin-right: 8px;
	}

	/* 评论区域样式 */
	.comments-section {
		background-color: #ffffff;
		padding: 15px;
		margin-bottom: 10px;
	}

	.comments-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 15px;
	}

	.comments-title {
		font-size: 14px;
		color: #333333;
		font-weight: bold;
	}

	.comments-info {
		display: flex;
		align-items: center;
	}

	.comments-count {
		font-size: 12px;
		color: #999999;
		margin-right: 8px;
	}

	.comments-preview {
		display: flex;
		flex-direction: column;
		gap: 15px;
	}

	.comment-preview-item {
		border-bottom: 1px solid #f0f0f0;
		padding-bottom: 15px;

		&:last-child {
			border-bottom: none;
			padding-bottom: 0;
		}
	}

	.comment-user {
		display: flex;
		align-items: center;
		margin-bottom: 8px;
	}

	.comment-avatar {
		width: 30px;
		height: 30px;
		border-radius: 50%;
		margin-right: 8px;
	}

	.comment-user-info {
		flex: 1;
	}

	.comment-username {
		font-size: 12px;
		color: #333333;
		font-weight: bold;
		display: block;
		margin-bottom: 2px;
	}

	.comment-rating {
		display: flex;
		gap: 1px;
	}

	.comment-content-text {
		font-size: 13px;
		color: #666666;
		line-height: 1.4;
		display: block;
	}

	/* 新增：评论图片 */
	.comment-images {
		display: flex;
		gap: 8px;
		margin-top: 8px;
	}

	.comment-img {
		width: 70px;
		height: 70px;
		border-radius: 6px;
		overflow: hidden;
		background: #f5f5f5;
	}

	.detail-section {
		background-color: #ffffff;
		padding: 15px;
		margin-bottom: 0;
	}

	.section-title {
		font-size: 16px;
		font-weight: bold;
		color: #333333;
		margin-bottom: 15px;
	}

	.detail-text {
		font-size: 14px;
		color: #666666;
		line-height: 1.6;
		margin-bottom: 15px;
		display: block;
	}

	.detail-images {
		display: flex;
		flex-direction: column;
	}

	.detail-image {
		width: 100%;
		margin-bottom: 10px;
	}

	.bottom-action-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #ffffff;
		border-top: 1px solid #f0f0f0;
		padding: 10px 15px;
		display: flex;
		align-items: center;
		z-index: 999;
	}

	.action-left {
		display: flex;
		flex: 1;
	}

	.action-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-right: 20px;
		position: relative;
	}

	.action-text {
		font-size: 10px;
		color: #666666;
		margin-top: 4px;
	}

	.cart-badge {
		position: absolute;
		top: -5px;
		right: -5px;
		background: linear-gradient(135deg, #1abc9c, #16a085);
		color: #ffffff;
		font-size: 10px;
		padding: 2px 6px;
		border-radius: 10px;
		min-width: 16px;
		text-align: center;
	}

	.action-right {
		display: flex;
		gap: 10px;
	}

	.add-cart-btn,
	.buy-now-btn {
		flex: 1;
		height: 40px;
		line-height: 40px;
		font-size: 14px;
		background: linear-gradient(135deg, #1abc9c, #16a085) !important;
		border: none !important;
		color: #ffffff !important;
		white-space: nowrap;
		min-width: 80px;
	}

	.buy-now-btn {
		background: linear-gradient(135deg, #e74c3c, #c0392b) !important;
	}
</style>